$(function () {


    var query = {},
        $update = $('.btn-update'),
        $delete = $('.btn-delete'),
        $batchUpdatePrice = $('.batch-update-price'),
        $batchUpdatePriceTpl = $('.batch-update-price-tpl'),
        $create = $('.btn-create'),
        $ups = $('.batch-up'),
        $group = $('.batch-group'),
        $log = $('.btn-log'),
        //$upload = $('.btn-chongdi'),
        $banners = $('.btn-allow'),
        $plus = $('.plus'),
        $refuse = $('.btn-refuse'),
        $detail = $('.btn-dist-role'),
        $import = $('.btn-chongdi'),
        $tpl = $('.btn-hexiao'),
        strHtml = $('#form-template').html();
    onClick($ups, function () { // 批量上架
        return window.location.href = '../../sys/category/dispatch-items.html?type1=ups';// 批量上架
    })
    /**
     * 分类产品
     */
    onClick($('.category-product'), function () {
        window.location = './dispatch-items.html?type=offer&name=';//
    });
    //批量更新价格
    onClick($batchUpdatePrice, function () {
        uploadFn('批量更新价格(请严格按模板字段批量批量更新价格)', {
            url: '/api/admin/offer/importUpdatePrice',
            num: 12,
            labelNum: '12 upload-custom-label',
            plain: true,// 普通文件，非图片文件
            noCrop: true,
        }, function (data) {
            closeLayer(data.layerIndex);
            console.log(data);//
            search({}, true);
            alert('导入成功');
        });
    })
    //批量更新价格模板
    onClick($batchUpdatePriceTpl, function () {
        window.open('/admin/libs/批量更新价格模板.xlsx', '_blank');

    })
    onClick($group, function () { // 批量拼团
        return window.location.href = '../../sys/category/dispatch-items.html?type1=groups';//批量拼团
    })

    var config = {
        query: '/offer/query?type2=1&',//分页查询URL,
        query_store: '/store/query?size=' + maxSize,//分页查询URL,
        create: '/offer/create',//create,
        plus: '/offer/plus',//create,//增加可售数量
        update: '/offer/update',
        queryAccount: '/payType/query?type=2',// // 供货地账户
        'delete': '/offer/delete'
    };
    enableBtn($tpl, {})
    enableBtn($import, {})
    onClick($tpl, function () {
        window.open('/admin/libs/批量上货模板.xlsx', '_blank');
    });
    fnLoading();;
    onClick($import, function () {
        //批量导入
        uploadFn('批量上货(请严格按模板字段批量上货)', {
            url: '/api/admin/offer/import',
            num: 12,
            labelNum: '12 upload-custom-label',
            plain: true,// 普通文件，非图片文件
            noCrop: true,
        }, function (data) {
            closeLayer(data.layerIndex);
            console.log(data);//
            search({}, true);
            if (data.data && data.data.length) {
                alert('导入成功, 货号为' + _.pluck(data.data[0], 'no').join(',') + '的数据因货号重复没有被导入！')
            } else {
                alert('导入成功')
            }
        });

    });
    onClick($refuse, function () {
        var $current = $(this).data('json');
        window.location = './../info/goods-info.html?id=' + $current.id + '&type=offer&name=' + $current.name;
    });
    onClick($log, function () {
        var $current = $(this).data('json');
        if(!$current)return;
        window.location = './../../log/log.html?id=' + $current.id + '&type=offer';
    });

    function filterFn(item, fieldName) {
        if (!item[fieldName])return '';
        return item[fieldName].split(',').map(function (item) {
            if (!item)return '';
            return window[fieldName][item] && window[fieldName][item] && window[fieldName][item][0].name;
        }).join(',');
    }

    function search(obj, isForce) {
        fnLoading();
        gSearch({
            url: config.query,
            query: obj,
            table: true,
            isForce: isForce,
            render: function (list, opt) {
                hideLoading();
                var _$table = $('.table-responsive .table');
                if (typeof list == 'string') {
                    return _$table.html(list);
                }
                destroyBtn();
                _$table.$table($.extend(TABLE_SETTING, {
                    checkbox: true, // 是否显示复选框
                    seqNum: true, // 是否显示序号
                    // sort: search, //排序回调函数
                    showSearchComplex: true,
                    destroyBtn: destroyBtn, //禁用按钮
                    createBtn: createBtn, // 启用她扭
                    toolbar: '.toolbar',
                    enableSetting: true,//允许自定义显示列
                    search: function (obj) { //搜索框查询函数
                        search(obj)
                    },
                    rendered: function () {
                        onClick($('.minQrCode-detail'),function(){
                            $.get('/offer/getShopQrCode?id='+$(this).data('id'),function(res){
                                if(res.code==200){
                                    window.open(res.error,'_blank');
                                }else{
                                    fnFail('打开失败')
                                }
                            })
                        })
                        $('.category-detail').each(function (index, item) {
                            var $item = $(item);
                            // onClick($('.category-detail'),function (e) {
                            //     e.stopPropagation();
                            var id = $item.data().id;
                            // var that = this;
                            $.get('/category/listDRBySourceId?targetId=' + id + '&type1=shop-category&dataRtype1=shop-category', function (res) {
                                console.log(res);
                                if (res.list && res.list.list) {
                                    if (res.list.list.length != 0) {
                                        $item.replaceWith('<span>' + _.pluck(res.list.list, 'name').join(',') + '<span>')
                                    } else {
                                        $item.replaceWith('<span>无<span>')
                                    }
                                }
                            })
                        })
                        hideLoading();
                        if (opt.lastSearchKey) {
                            searchInputValue(opt.lastSearchKey);
                        }
                        if (window.categoryId && !$('[name=categoryId]').data('init')) {//
                            var filterObj = lsGet(opt.lastSearchKey);
                            getClassifiedQuery({url: '/category/listSummary?type1=shop-category&size=10000'}, function (res) {
                                var categorys2 = res
                                selectpickerFn({
                                    ele: $('[name=categoryId]'),
                                    name: 'categoryId',
                                    label: '请选择分类',
                                    placeholder: '所有分类',
                                    selected: categorys2.id || '',
                                    list: categorys2,
                                    change: function (id) {
                                        console.log(id);
                                        $('[name=categoryId]').val(id);
                                        search({categoryId: id, page: 1}, true)
                                    }
                                })
                            })

                            selectpickerFn({
                                ele: $('[name=brand]'),
                                name: 'brand',
                                label: '请选择品牌',
                                selected: filterObj.brand || '',
                                placeholder: '所有商品品牌',
                                list: _.flatten(_.values(window.brand)),
                                change: function (id) {
                                    console.log(id);
                                    search({brand: id, page: 1}, true)
                                }
                            })
                            selectpickerFn({
                                ele: $('[name=online]'),
                                name: 'online',
                                label: '请选择状态',
                                selected: filterObj.online ||'',
                                placeholder: '请选择状态',
                                list: [
                                    {
                                        id:0,
                                        name:'下架'
                                    },
                                    {
                                        id:1,
                                        name:"上架"
                                    }],
                                change: function (id) {
                                    search({status: id, page: 1}, true)
                                }
                            })
                        }
                    },
                    fields: [
                        {
                            name: 'thumbnail', label: '缩略图',
                            filter: function (item) {
                                if (item.thumbnail) {
                                    return '<a target="_blank" href="' + item.thumbnail +
                                        '" title="点击预览"><img style="height:60px;border-radius:5px;" src="' + item.thumbnail + '" /></a>'
                                } else {
                                    return getDefaultImgStr();
                                }
                            }
                        },
                        {name: 'id', label: '商品ID'},
                        {name: 'id', label: '商品小程序码',filter:function(item){
                                return '<a href="javascript:void(0);" class="minQrCode-detail" data-id="'+item.id+'" >查看</a>'
                            }},
                        {name: 'code', label: '货号', enableSearch: true},
                        {name: 'name', label: '商品名称', enableSearch: true},
                        {
                            name: 'desc1', label: '描述', filter: function (item) {
                                return viewMore(item.desc1 || ''); // 预览更多内容
                            }
                        },
                        {
                            name: 'brand', label: '品牌', enableSearch: true, filter: function (item) {

                                return item.brandName;
                            }
                        },

                        {
                            name: 'price', label: '原价',
                            filter: function (item) {
                                if (item.priceMin == item.price)return item.price;
                                return item.priceMin + '-' + item.price;
                            }
                        },
                        {
                            name: 'costPrice', label: '成本价',
                        },
                        {
                            name: 'actualPrice', label: '现价',
                            filter: function (item) {
                                if (item.actualPrice == item.actualPriceMin)return item.actualPrice;
                                return item.actualPriceMin + '-' + item.actualPrice;

                            }
                        },
                        {
                            name: 'ptPrice', label: '拼团价',
                            filter: function (item) {
                                if (item.ptPriceMin == item.ptPrice)return item.ptPrice;
                                return item.ptPriceMin + '-' + item.ptPrice;

                            }
                        },
                        {
                            name: 'online', label: '状态',
                            filter: function (item) {
                                return item.status == '1' ? '<span class="label label-success">上架</span>' : '<span class="label label-warning">下架</span>';
                            },
                            enableSearch: true,
                        },
                        {
                            name: 'deliverPlace', label: '供货地',
                            filter: function (item) {
                                return filterFn(item, 'deliverPlace');
                            }
                        },
                        {
                            enableSearch: true,
                            name: 'categoryId', label: '类别', filter: function (item) {
                                return '<a href="javascript:void(0)" ' +
                                    '' +
                                    'data-id="' + item.id + '" class="category-detail">查看</a>';
                                // return filterFn(item, 'categoryId');
                            }
                        },
                        // {
                        //     name: 'goodsName', label: '折扣活动',
                        //     filter: function (item) {
                        //         return filterFn(item, 'discountId');
                        //     }
                        // },
                        {
                            name: 'tags', label: '标签',
                            filter: function (item) {
                                return item.tags
                            }
                        },
                        {
                            name: 'saleNum', label: '库存',
                            filter: function (item) {
                                return item.saleNum
                            }
                        },
                    ],
                    data: list || [],
                }));
            }
        }, false);
    }

    function getGoods(item, isUpdate) {
    }
    onClick($update, function () {
        var $current = $(this).data('json'), self = this;//
        return window.location.href = './edit.html?id=' + $current.id;
    });
    onClick($create, function () {//
        return window.location.href = './edit.html';//
    });

    onClick($delete, function () {
        var $current = $(this).data('json'), self = this;
        if(!$current)return;
        // $(self).button('loading');
        if (confirm('确认删除"' + $(this).data('json').name + '"?')) {
            $.post(config['delete'], {id: $current.id}, function (xhr, data) {
                $(self).button('reset');
                if (xhr.code == 200) {
                    fnSuccess('删除成功!');
                    $('tr[id=' + $current.id + ']').remove();
                    // $(self).closest('tr').remove();
                    setTimeout(function () {
                        destroyBtn();
                    }, 0)
                } else {
                    alert('删除失败：' + xhr.error);
                }
            })
        } else {
            // $(self).button('reset');
        }
    });

    $.when(
        // parent.window.getDataByUrl(config.queryAccount, "deliverPlaces"),
        $.get('/category/listSummary?type1=deliverPlaces&size=10000'),
        // $.get('/category/listSummary?type1=color&size=10000'),
        // $.get('/category/listSummary?type1=season'),
        $.get('/category/listSummary?type1=shop-category&level=2&size=10000'),
        $.get('/category/listSummary?type1=brand&size=10000')
        // $.get('/category/listSummary?type1=country&size=10000'),
        // $.get('/category/listSummary?type1=sizeId&size=10000'),
        // $.get('/category/listSummary?type1=discount&size=10000'),
        // $.get('/tpl/listWithoutContent?type1=3&size=10000'),// 尺码对照表
        // $.get('/category/listSummary?type1=age&size=10000')
    )
        .then(function (country,category,brand) {

            search({}, true);
            // color = color[0].list;
            // season = season[0].list;
            brand = brand[0].list;
            // discount = discount[0].list;
            country = country[0].list;
            // age = age[0].list;
            // sizeId = sizeId[0].list;
            category = category[0].list;
            // sizeTable = sizeTable[0].list;

            // window.color = _.groupBy(color, 'id');
            // window.sizeTable = _.groupBy(sizeTable, 'id');
            // window.season = _.groupBy(season, 'id');
            window.brand = _.groupBy(brand, 'id');
            // window.discountId = _.groupBy(discount, 'id');
            window.deliverPlace = _.groupBy(country, 'id');
            // window.applyAge = _.groupBy(age, 'id');
            // window.sizeId = _.groupBy(sizeId, 'id');

            window.categoryId = _.groupBy(category, 'id');
        })

    function destroyBtn() {
        $update.data('json', null);
        $delete.data('json', null);
        disableBtn($update);
        disableBtn($plus);
        disableBtn($log);
        disableBtn($delete);
        //disableBtn($upload);
        disableBtn($refuse);
        disableBtn($banners);
        disableBtn($detail);
    }

    function createBtn(_this) {
        destroyBtn();
        var item = $(_this).data('json');
        enableBtn($update, item);
        enableBtn($log, (item));
        enableBtn($plus, (item));
        enableBtn($delete, item);
        //enableBtn($upload, item);
        enableBtn($refuse, item);
        enableBtn($banners, item);
        enableBtn($detail, item);
    }

    function validate(modal, obj) {
        console.log('000')
        $('#registrationForm')
        // .find('[name="color"]')
        // .selectpicker({
        //     liveSearch: true,
        // })
        // .change(function (e) {
        //     $('#registrationForm').data('formValidation').revalidateField('color');
        // })
        // .end()
        // .find('[name="sizeId"]')
        // .selectpicker({
        //     liveSearch: true,
        // })
        // .change(function (e) {
        //     $('#registrationForm').data('formValidation').revalidateField('sizeId');
        // })
        // .end()
        // .find('[name="applyAge"]')
        // .selectpicker({
        //     liveSearch: true,
        // })
        // .change(function (e) {
        //     $('#registrationForm').data('formValidation').revalidateField('applyAge');
        // })
        // .end()
        // .find('[name="season"]')
        // .selectpicker({
        //     liveSearch: true,
        // })
        // .change(function (e) {
        //     $('#registrationForm').data('formValidation').revalidateField('season');
        // })
        // .end()
            .find('[name="categoryId"]')
            .selectpicker({
                liveSearch: true,
            })
            .change(function (e) {
                $('#registrationForm').data('formValidation').revalidateField('categoryId');
            })
            .end()
            // .find('[name="discountId"]')
            // .selectpicker({
            //     liveSearch: true,
            // })
            // .change(function (e) {
            //     $('#registrationForm').data('formValidation').revalidateField('discountId');
            // })
            // .end()
            // .find('[name="deliverPlace"]')
            // .selectpicker({
            //     liveSearch: true,
            // })
            // .change(function (e) {
            //     $('#registrationForm').data('formValidation').revalidateField('deliverPlace');
            // })
            // .end()
            .find('[name="brand"]')
            .selectpicker({
                liveSearch: true,
            })
            .change(function (e) {
                $('#registrationForm').data('formValidation').revalidateField('brand');
            })
            .end();
        // obj.color && $('[name="color"]').selectpicker('val', obj.color.split(','));
        // obj.season && $('[name="season"]').selectpicker('val', obj.season.split(','));
        obj.categoryId && $('[name="categoryId"]').selectpicker('val', obj.categoryId.split(','));
        // obj.discountId && $('[name="discountId"]').selectpicker('val', obj.discountId.split(','));
        obj.brand && $('[name="brand"]').selectpicker('val', obj.brand.split(','));

        // $('#registrationForm').formValidation('destroy')
        //     .formValidation($.extend({}, VALIDATION_SETTING, {
        //         fields: {
        //             name: {
        //                 row: '.col-xs-7',
        //                 validators: {
        //                     notEmpty: {
        //                         message: '报价名称必填'
        //                     },
        //                     stringLength: {
        //                         min: 3,
        //                         max: 40,
        //                         message: '报价名称长度最少3位，最多40位'
        //                     }
        //                 }
        //             },
        //
        //             price: {
        //                 row: '.col-xs-7',
        //                 validators: {
        //                     notEmpty: {
        //                         message: '货物单价必填'
        //                     },
        //                     greaterThan: {
        //                         value: 0,
        //                         message: '单价必须大于0'
        //                     },
        //                     // numeric: {
        //                     //     message: '单价必须是数字',
        //                     // }
        //                 }
        //             },
        //             priceUnit: {
        //                 row: '.col-xs-7',
        //                 validators: {
        //                     notEmpty: {
        //                         message: '价格单位必填'
        //                     },
        //                 }
        //             },
        //             unit: {
        //                 row: '.col-xs-7',
        //                 validators: {
        //                     notEmpty: {
        //                         message: '计量单位必填'
        //                     },
        //                 }
        //             },
        //             qualitySpec: {
        //                 row: '.col-xs-7',
        //                 validators: {
        //                     notEmpty: {
        //                         message: '品质规格必填'
        //                     },
        //                 }
        //             },
        //             packSpec: {
        //                 row: '.col-xs-7',
        //                 validators: {
        //                     notEmpty: {
        //                         message: '包装规格必填'
        //                     },
        //                 }
        //             },
        //
        //             qualityRequire: {
        //                 row: '.col-xs-7',
        //                 validators: {
        //                     notEmpty: {
        //                         message: '质量标准必选'
        //                     },
        //                 }
        //             },
        //             salesMan: {
        //                 row: '.col-sm-6',
        //                 validators: {
        //                     notEmpty: {
        //                         message: '销售员佣金必填'
        //                     },
        //                 }
        //             },
        //             salesManager: {
        //                 row: '.col-sm-6',
        //                 validators: {
        //                     notEmpty: {
        //                         message: '销售经理佣金必填'
        //                     },
        //                 }
        //             },
        //         }
        //     }))
        //     .off('success.form.fv')
        //     .on('success.form.fv', function (e) {
        //         e.preventDefault();
        //         var form = parseSearch($(e.target).serialize());
        //         var url = '';
        //         if (form.id) { // is update?
        //             url = config.update;
        //         } else {
        //             url = config.create;
        //             delete form.id;
        //         }
        //         if (form.name) {
        //             form.name = form.name.trim();
        //         }
        //
        //         if (form.priceUnit) {
        //             form.priceUnit = form.priceUnit.replace('%2F', '/')
        //         }
        //         form.actualPrice = form.price;
        //
        //         if (!!form.color) {
        //             form.color = [',', form.color, ','].join('')
        //         }
        //         if (!!form.season) {
        //             form.season = [',', form.season, ','].join('')
        //         }
        //         if (!!form.sizeId) {
        //             form.sizeId = [',', form.sizeId, ','].join('')
        //         }
        //         if (!!form.applyAge) {
        //             form.applyAge = [',', form.applyAge, ','].join('')
        //         }
        if (!!form.categoryId) {
            form.categoryId = [',', form.categoryId, ','].join('')
        }
        //         form.salesManager = 0;
        //         $.post(url, form, function (xhr, data) {
        //             if (xhr.code == 200) {
        //                 fnSuccess(form.id ? '保存成功' : '创建成功!');
        //                 search({}, true);
        //                 window.$index && closeLayer(window.$index);
        //             } else {
        //                 alert(xhr.error || xhr.msg);
        //             }
        //         });
        //     });
    }
});